package com.yanqu.road.server.cmd.activity.jiuzhou;

import com.yanqu.road.entity.activity.jiuzhou.CrossJiuZhouPatronsData;
import com.yanqu.road.logic.pb.JiuZhouPb;
import com.yanqu.road.message.YanQuMessage;

import com.yanqu.road.pb.activity.jiuzhou.CrossJiuZhouProto;
import com.yanqu.road.pb.activity.jiuzhou.JiuZhouProto;
import com.yanqu.road.pb.patrons.PatronsProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.jiuzhou.CrossJiuZhouMgr;
import com.yanqu.road.server.manager.activity.jiuzhou.activity.CrossJiuZhouActivity;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Cmd(code = CrossProtocol.C_JIU_ZHOU_SIGN_UP, desc = "跨服九州棋局报名")
public class CrossJiuZhouSignUpCmd extends CrossCommand {

    private int activityId;

    private BigInteger ability;

    private int grade;

    private List<PatronsProto.PatronsSimpleTempMsg> patronsDataTempList = new ArrayList<>();

    private long playerId;
    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        CrossJiuZhouProto.CrossJiuZhouSignUpReqMsg reqMsg = CrossJiuZhouProto.CrossJiuZhouSignUpReqMsg.parseFrom(packet.getBytes());
        activityId = reqMsg.getActivityId();
        ability = new BigInteger(reqMsg.getNowMaxAbility());
        patronsDataTempList = reqMsg.getPatronsDataList();
        playerId = packet.getPlayerId();
        grade = reqMsg.getMonthRankGrade();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        CrossJiuZhouActivity activity = CrossJiuZhouMgr.getActivity(activityId);
        if (activity == null) {
            ret = GameErrorCode.E_JIU_ZHOU_ACTIVITY_NOT_EXIST;
            return;
        }
        List<CrossJiuZhouPatronsData> patronsDataList = new ArrayList<>();
        // 门客数据
        for (PatronsProto.PatronsSimpleTempMsg tempMsg : patronsDataTempList) {
            CrossJiuZhouPatronsData data = JiuZhouPb.parseCrossJiuZhouPatronsData(tempMsg);
            if (data == null) {
                continue;
            }
            patronsDataList.add(data);
        }
        ret = activity.signUp(playerId,grade, ability, patronsDataList);
    }

    @Override
    public void sendData() {
        if (ret != 0){
            JiuZhouProto.SignUpJiuZhouRespMsg.Builder builder = JiuZhouProto.SignUpJiuZhouRespMsg.newBuilder();
            builder.setRet(ret);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_JIU_ZHOU_SIGN_UP_FROM_CROSS, builder));
        }
    }
}
